package it.secse.idmadaption.parser;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMNode;
import org.apache.axiom.om.OMText;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.OMTextImpl;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.xerces.parsers.DOMParser;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ConfigParser implements ParserIF {
	
	private static final String ConfigDir = "files";
	private Document doc = null;

	public ConfigParser(String opName) {
		if (doc == null) {
			DOMParser parser = new DOMParser();
			try {
				parser.parse(ConfigDir + "/" + opName + ".xml");
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			doc = parser.getDocument();
		}

	}
	
	public Document getDocument(){
		return doc;
	}


	
	public String getPlugin() {
		NodeList nodes = doc.getElementsByTagName("AccessMethod");
		Node node = nodes.item(0);
		String pluginName = node.getFirstChild().getNodeValue();
		System.out.println(pluginName);
		return pluginName;

	}

	
	public String getServiceNamespace() {
		// TODO Auto-generated method stub
		return null;
	}
	
    public static Policy loadPolicy(String opName) throws FileNotFoundException, XMLStreamException  {
        StAXOMBuilder builder = new StAXOMBuilder(ConfigDir + File.separator + "google/policy.xml");
        OMElement elem = builder.getDocumentElement();
        OMNode app1 = elem.getFirstElement().getFirstElement().getFirstElement().getNextOMSibling().getNextOMSibling().getNextOMSibling().getNextOMSibling();
        app1.serialize(System.out);
 //     System.out.println("ECCO:  " + ((OMTextImpl)elem.getFirstChildWithName(new QName("http://schemas.xmlsoap.org/ws/2005/07/securitypolicy","TransportBinding","sp"))).getText());
        return PolicyEngine.getPolicy(builder.getDocumentElement());
        
    }

 //   "D:\\policy\\google\\policy.xml"
}
